<?php
// No direct access
defined ('_JEXEC') or die();

jimport ('joomla.application.component.controllerform');

class ShipnhanhControllerPrepaid extends JControllerForm
{
	public function __construct($config = array())
	{
		$this->view_list = 'prepaids';
		parent::__construct($config);
	}
	
	public function save($key = null, $urlVar = null)
	{
		$model = JModel::getInstance('Prepaids', 'ShipnhanhModel');
		$data = JRequest::getVar('jform', array(), 'post', 'array');
		
		if (! $model->isEmailExisted($data['email']) || $data['id'] > 0)
		{
			parent::save($key, $urlVar);
		}
		else
		{
			$this->setMessage(JText::_('COM_SHIPNHANH_SHIPNHANH_ERROR_DATA_EXISTED'), 'error');
			$this->setRedirect(
					JRoute::_(
							'index.php?option=' . $this->option . '&task=prepaid.edit'
							. '&id='. $data['id'], false
					)
			);
			
			return false;
		}
	}
	
	public function postSaveHook($model, $validData) 
	{
		$item = $model->getItem();
        $id = $item->get('id'); 
		$amount = $item->get('amount');
		$model = JModel::getInstance('Prepaids', 'ShipnhanhModel');
		$model->insertHistory($id, $amount, JText::_('COM_SHIPNHANH_SHIPNHANH_NEW_PREPAID'));
	}
	
	public function update()
	{
		$ids = JRequest::getVar('cid', array(), 'post', 'array');
		$model = JModel::getInstance('Prepaids', 'ShipnhanhModel');
		
		// Update data
		$prepaidId = JRequest::getVar('prepaidid');
		$vndPrice = JRequest::getVar('vndprice');
		$model->updatePrepaid($prepaidId, JRequest::getVar('remain'));
		$model->insertHistory(JRequest::getVar('prepaidid'), JRequest::getVar('remain'), JText::sprintf('COM_SHIPNHANH_SHIPNHANH_UPDATE_PREPAID', $vndPrice));
		
		// Redirect to request page
		$url = JFactory::getURI();
		$app = JFactory::getApplication();
		$app->setUserState("ids", $ids);
		
		$this->setRedirect($url . '?option=' . $this->option . '&task=order.billout');
	}
}